//
//  MessageViewController.m
//  Before
//
//  Created by lanou3g on 15/11/30.
//  Copyright © 2015年 sss. All rights reserved.
//

#import "MessageViewController.h"
#import "SendViewController.h"
#import "AVOSCloud.h"
#import "NoPhotosTableViewCell.h"
#import "onePhotoTableViewCell.h"
#import "twoPhotosTableViewCell.h"
#import "threePhotosTableViewCell.h"
#import "fourPhotosTableViewCell.h"
#import "MBProgressHUD.h"
#import "currentState.h"
#import "ScreenViewController.h"
#import "CommentsViewController.h"
@interface MessageViewController ()<UITabBarDelegate,UITableViewDataSource,UITableViewDelegate,NoPhotoTabelViewDelegate,onePhotoTabelViewDelegate,twoPhotoTabelViewDelegate,threePhotoTabelViewDelegate,fourPhotoTabelViewDelegate>
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)NSMutableArray * dataArray;
@property (nonatomic,strong)AVQuery * query;
@property (nonatomic,assign)float height;
@property (nonatomic,strong)MBProgressHUD * hud;

@end

@implementation MessageViewController

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"微博列表";
    // AVQuery
    self.query = [AVQuery queryWithClassName:@"Post"];
    [self.query orderByDescending:@"createdAt"];
    // 分割线
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];
    // tableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
//    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"1"]];
    [self.view addSubview:self.tableView];
    // 注册cell
    [self.tableView registerClass:[NoPhotosTableViewCell class] forCellReuseIdentifier:@"noPhotoCell"];
    [self.tableView registerClass:[onePhotoTableViewCell class] forCellReuseIdentifier:@"onePhotoCell"];
    [self.tableView registerClass:[twoPhotosTableViewCell class] forCellReuseIdentifier:@"twoPhotoCell"];
    [self.tableView registerClass:[threePhotosTableViewCell class] forCellReuseIdentifier:@"threePhotoCell"];
    [self.tableView registerClass:[fourPhotosTableViewCell class] forCellReuseIdentifier:@"fourPhotoCell"];
    
    //
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"我要发微博" style:(UIBarButtonItemStylePlain) target:self action:@selector(leftAction:)];
       
    //    self.tableView.estimatedRowHeight = 100;
    //    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.dataArray = [NSMutableArray array];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
   
}

- (void)loadData
{
    [self.query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            [self.dataArray setArray:objects];
            [self.tableView reloadData];
        }
        
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AVObject * object = self.dataArray[indexPath.row];
    // 时间转换字符串
    NSDate * date = [object objectForKey:@"createdAt"];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd HH:mm:ss"];
    NSString * timeStr = [formatter stringFromDate:date];

    // 获取 图片文件
    AVFile * first = [object objectForKey:@"firstImage"];
    AVFile * second = [object objectForKey:@"secondImage"];
    AVFile * third = [object objectForKey:@"thirdImage"];
    AVFile * fourth = [object objectForKey:@"fourthImage"];
    if (first == nil) {
        NoPhotosTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"noPhotoCell" forIndexPath:indexPath];
        // 减缓 卡顿
        cell.layer.shouldRasterize = YES;
        cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
        // 内容
        cell.myTextLabel.text = [object objectForKey:@"message"];
        // 名字
        cell.nameLabel.text = [object objectForKey:@"userName"];
        // 时间
        cell.timeLabel.text = timeStr;
//        // 位置
//        cell.locationLabel.text = [object objectForKey:@"location"];
        // 点赞
        cell.delegate = self;
        cell.praiseButton.buttonIndex = indexPath;
        NSNumber * n = [object objectForKey:@"praiseNumber"];
        NSString * s = [NSString stringWithFormat:@"%@",n];
        cell.praiseLabel.text = s;
        // 评论
        cell.commentButton.buttonIndex = indexPath;
      
        // 头像
        AVFile * attachment = [object objectForKey:@"userImage"];
        cell.myImageView.layer.masksToBounds = YES;
        AVFile * file = [AVFile fileWithURL:attachment.url];
        [file getThumbnail:YES width:50 height:50 withBlock:^(UIImage *image, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.myImageView.image = image;
            });
        }];
        return cell;

    }else if(second == nil)
    {
        onePhotoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"onePhotoCell" forIndexPath:indexPath];
        // 减缓 卡顿
        cell.layer.shouldRasterize = YES;
        cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
        // 内容
        cell.myTextLabel.text = [object objectForKey:@"message"];
        // 名字
        cell.nameLabel.text = [object objectForKey:@"userName"];
        // 时间
        cell.timeLabel.text = timeStr;
               // 点赞
        cell.delegate = self;
        cell.praiseButton.buttonIndex = indexPath;
        NSNumber * n = [object objectForKey:@"praiseNumber"];
        NSString * s = [NSString stringWithFormat:@"%@",n];
        cell.praiseLabel.text = s;
        // 评论
        cell.commentButton.buttonIndex = indexPath;
        // 头像
        AVFile * attachment = [object objectForKey:@"userImage"];
        cell.myImageView.layer.masksToBounds = YES;
        AVFile * file = [AVFile fileWithURL:attachment.url];
        [file getThumbnail:YES width:50 height:50 withBlock:^(UIImage *image, NSError *error) {
          
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.myImageView.image = image;
            });
            
        }];
        // 第一张图片
        AVFile * onePhotoFile = [AVFile fileWithURL:first.url];
        [onePhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.firstImageView.image = image;
            });
        }];
        
        
        return cell;
        
    }
    else if(third == nil) {
      twoPhotosTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"twoPhotoCell" forIndexPath:indexPath];
        // 减缓 卡顿
        cell.layer.shouldRasterize = YES;
        cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
        // 内容
        cell.myTextLabel.text = [object objectForKey:@"message"];
        // 名字
        cell.nameLabel.text = [object objectForKey:@"userName"];
        // 时间
        cell.timeLabel.text = timeStr;
        // 点赞
        cell.delegate = self;
        cell.praiseButton.buttonIndex = indexPath;
        NSNumber * n = [object objectForKey:@"praiseNumber"];
        NSString * s = [NSString stringWithFormat:@"%@",n];
        cell.praiseLabel.text = s;
        // 评论
        cell.commentButton.buttonIndex = indexPath;


        // 头像
        AVFile * attachment = [object objectForKey:@"userImage"];
        AVFile * file = [AVFile fileWithURL:attachment.url];
        [file getThumbnail:YES width:50 height:50 withBlock:^(UIImage *image, NSError *error) {
         
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.myImageView.image = image;
            });
            
        }];
        // 第一张图片
        AVFile * onePhotoFile = [AVFile fileWithURL:first.url];
        [onePhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.firstImageView.image = image;
            });
        }];
        // 第二张 图片
        AVFile * twoPhotoFile = [AVFile fileWithURL:second.url];
        [twoPhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
           
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.secondImageView.image = image;
            });
        }];
        return cell;
    }else if (fourth == nil){
        threePhotosTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"threePhotoCell" forIndexPath:indexPath];
        // 减缓 卡顿
        cell.layer.shouldRasterize = YES;
        cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
        // 内容
        cell.myTextLabel.text = [object objectForKey:@"message"];
        // 名字
        cell.nameLabel.text = [object objectForKey:@"userName"];
        // 时间
        cell.timeLabel.text = timeStr;
        // 点赞
        cell.delegate = self;
        cell.praiseButton.buttonIndex = indexPath;
        NSNumber * n = [object objectForKey:@"praiseNumber"];
        NSString * s = [NSString stringWithFormat:@"%@",n];
        cell.praiseLabel.text = s;
        // 评论
        cell.commentButton.buttonIndex = indexPath;
        


        // 头像
        AVFile * attachment = [object objectForKey:@"userImage"];
        AVFile * file = [AVFile fileWithURL:attachment.url];
        [file getThumbnail:YES width:50 height:50 withBlock:^(UIImage *image, NSError *error) {
                      dispatch_async(dispatch_get_main_queue(), ^{
                cell.myImageView.image = image;
            });
            
        }];
        // 第一张图片
        AVFile * onePhotoFile = [AVFile fileWithURL:first.url];
        [onePhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.firstImageView.image = image;
            });
        }];
        // 第二张 图片
        AVFile * twoPhotoFile = [AVFile fileWithURL:second.url];
        [twoPhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.secondImageView.image = image;
            });
        }];
 
        // 第三张 图片
        AVFile * threePhotoFile = [AVFile fileWithURL:second.url];
        [threePhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.thirdImageView.image = image;
            });
        }];

        return cell;
     }else
     {
         
         fourPhotosTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"fourPhotoCell" forIndexPath:indexPath];
         // 减缓 卡顿
         cell.layer.shouldRasterize = YES;
         cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
         // 内容
         cell.myTextLabel.text = [object objectForKey:@"message"];
         // 名字
         cell.nameLabel.text = [object objectForKey:@"userName"];
         // 时间
         cell.timeLabel.text = timeStr;
         // 点赞
         cell.delegate = self;
         cell.praiseButton.buttonIndex = indexPath;
         NSNumber * n = [object objectForKey:@"praiseNumber"];
         NSString * s = [NSString stringWithFormat:@"%@",n];
         cell.praiseLabel.text = s;
         // 评论
         cell.commentButton.buttonIndex = indexPath;
         // 头像
         AVFile * attachment = [object objectForKey:@"userImage"];
         AVFile * file = [AVFile fileWithURL:attachment.url];
         [file getThumbnail:YES width:50 height:50 withBlock:^(UIImage *image, NSError *error) {
           
             dispatch_async(dispatch_get_main_queue(), ^{
                 cell.myImageView.image = image;
             });
             
         }];
         // 第一张图片
         AVFile * onePhotoFile = [AVFile fileWithURL:first.url];
         [onePhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 cell.firstImageView.image = image;
             });
         }];
         // 第二张 图片
         AVFile * twoPhotoFile = [AVFile fileWithURL:second.url];
         [twoPhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 cell.secondImageView.image = image;
             });
         }];
         
         // 第三张 图片
         AVFile * threePhotoFile = [AVFile fileWithURL:second.url];
         [threePhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 cell.thirdImageView.image = image;
             });
         }];
         // 第三张 图片
         AVFile * fourPhotoFile = [AVFile fileWithURL:second.url];
         [fourPhotoFile getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 cell.fourthImageView.image = image;
             });
         }];

         
         return cell;

         
     }
    
    return nil;
}


// 点赞方法
- (void)praiseButton:(CellButton *)aButton
{
    if ([currentState defaultState].isLoading == YES) {
        AVObject * object = self.dataArray[aButton.buttonIndex.row];
        AVUser * user = [AVUser currentUser];
        NSString * string = [user.objectId stringByAppendingString:@"s"];
        NSString * s = [object objectForKey:string];
        
        if (![s isEqualToString:user.objectId]) {
            [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                [object setObject:user.objectId forKey:string];
                // 增加点赞的人数
                [object incrementKey:@"praiseNumber"];
                [object saveInBackground];
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [self.tableView reloadData];
                });
            }];
            
        }else
        {
            [self showLetter:@"已赞过"];
        }

    }else
    {
        
        
        [self showLetter:@"请先登录"];
        
        
    }
    }
// 评论方法
- (void)commentButton:(CellButton *)aButton
{
    
    if ([currentState defaultState].isLoading == YES) {
        AVObject * object = self.dataArray[aButton.buttonIndex.row];
        CommentsViewController * commentVC = [[CommentsViewController alloc] init];
        commentVC.myObject = object;
        
        [self.navigationController pushViewController:commentVC animated:YES];

         }else{
        [self showLetter:@"请先登录"];
      }
}
// MBP 展示的方法
- (void)showLetter:(NSString *)title
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.mode = MBProgressHUDModeText;
    self.hud.labelText = title;
    [self.hud hide:YES afterDelay:2];
    
}

- (void)leftAction:(id)sender
{
    if ([currentState defaultState].isLoading == YES) {
        SendViewController * sendVC = [[SendViewController alloc] init];
        
        [self.navigationController pushViewController:sendVC animated:YES];
    }else
    {
        
        [self showLetter:@"请先登录"];
        
        
    }
  
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AVObject * object = self.dataArray[indexPath.row];
    NSString * s = [object objectForKey:@"message"];
    
    CGRect c = [s boundingRectWithSize:CGSizeMake(self.tableView.frame.size.width - 20, 0) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:18.5000000f]} context:nil];
    
    self.height = c.size.height;
    
    AVFile * first = [object objectForKey:@"firstImage"];
    AVFile * fourth = [object objectForKey:@"fourthImage"];
    if (first == nil) {
        return 100 + self.height;
    }else if (fourth != nil) {
        return 300 + self.height + 30;
    }else
    {
        return 200 + 30 + self.height;
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
